package com.itheima.behaviour.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.behaviour.dto.FollowBehaviorDto;
import com.itheima.behaviour.feign.ApBehaviourEntryFeign;
import com.itheima.behaviour.pojo.ApBehaviorEntry;
import com.itheima.behaviour.pojo.ApFollowBehavior;
import com.itheima.behaviour.mapper.ApFollowBehaviorMapper;
import com.itheima.behaviour.service.ApFollowBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * APP关注行为表 服务实现类
 * </p>
 *
 * @author 作者
 * @since 2021-08-30
 */
@Service
public class ApFollowBehaviorServiceImpl extends ServiceImpl<ApFollowBehaviorMapper, ApFollowBehavior> implements ApFollowBehaviorService {

    @Autowired
    private ApFollowBehaviorMapper apFollowBehaviorMapper;

    @Autowired
    private ApBehaviourEntryFeign apBehaviourEntryFeign;

    /***
     * 关注行为记录
     * @param dto
     */
    @Override
    public void addFollowBehavior(FollowBehaviorDto dto) {
        //0:获取Entry对象（用户信息）
        Result<ApBehaviorEntry> entryResult = apBehaviourEntryFeign.getByEquipmentIdOrUserId(null,dto.getUserId());
        ApBehaviorEntry entry = entryResult.getData();

        if(entry!=null){
            //1:查询数据库中是否存在该数据
            QueryWrapper<ApFollowBehavior> followBehaviorQueryWrapper = new QueryWrapper<ApFollowBehavior>();
            followBehaviorQueryWrapper.eq("entry_id",entry.getId());
            followBehaviorQueryWrapper.eq("follow_id",dto.getFollowId());
            ApFollowBehavior apFollowBehavior = apFollowBehaviorMapper.selectOne(followBehaviorQueryWrapper);

            //2:如果不存在，则添加该关注行为
            if(apFollowBehavior==null){
                apFollowBehavior = new ApFollowBehavior();
                apFollowBehavior.setEntryId(entry.getId());
                apFollowBehavior.setArticleId(dto.getArticleId());
                apFollowBehavior.setFollowId(dto.getFollowId());
                apFollowBehavior.setCreatedTime(LocalDateTime.now());
                apFollowBehaviorMapper.insert(apFollowBehavior);
            }else{//3:如果存在，则修改创建时间即可
                apFollowBehavior.setCreatedTime(LocalDateTime.now());
                apFollowBehaviorMapper.updateById(apFollowBehavior);
            }
        }
    }
}
